﻿#include "cmdframe.h"

using namespace IGBTProtocol;

unsigned char CmdFrame::_cmdSNCount = 0;
CmdFrame::CmdFrame()
    : BaseFrame()
{
    _frameHeader = FrameHeader_Cmd;
    _cmdType = Cmd_Undef;
}

CmdFrame::CmdFrame(CmdType cmdType, unsigned int cmdDataSize)
    : BaseFrame(FrameHeader_Cmd, cmdDataSize)
{
    _cmdType = cmdType;
}

CmdType CmdFrame::judge(QByteArray* buff)
{
    unsigned short cmd;
    cmd = (unsigned char)(buff->at(10));
    cmd <<= 8;
    cmd += (unsigned char)(buff->at(9));
    if(cmd != Cmd_ExecRes)
     return Cmd_Undef;
    else return Cmd_ExecRes;
}

bool CmdFrame::depack(QByteArray* buff)
{
    if(!BaseFrame::depack(buff))
        return false;

    _cmdType = judge(buff);
    if(_cmdType != Cmd_ExecRes)
        return false;

    _cmdCount = (unsigned char)(buff->at(11));
    return true;
}

unsigned int CmdFrame::frame(QByteArray* buff, bool tail)
{
    BaseFrame::frame(buff);

    buff->append(_cmdType & 0x00ff);
    buff->append(_cmdType >> 8);

    buff->append(_cmdSNCount);
    _cmdSNCount++;

    if(!tail)
        return 12;

    for(unsigned int i=3;i<_dataSize;i++)
        buff->append((char)0);

    buff->append(calcCRC(buff,_dataSize + 7));
    return 8+_dataSize;
}
